# -*- coding: utf-8 -*-
from pymongo import UpdateOne
from zc_core.client.mongo_client import Mongo
from zc_core.util.sku_id_parser import convert_id2code

from huiemall.matcher import match_sp_sku_id_from_img


def update_status(year):
    mongo = Mongo(year=year)
    bulk_list = list()
    items = mongo.list('item_data_pool', fields={'_id': 1, 'skuImg': 1, 'supplierName': 1})
    for item in items:
        sku_id = item.get('_id')
        img = item.get('skuImg')
        sp_name = item.get('supplierName')
        sp_sku_id = match_sp_sku_id_from_img(img)
        if sp_sku_id:
            item['supplierSkuId'] = sp_sku_id
            if sp_sku_id and sp_name:
                sp_sku_code = sp_sku_id
                if '得力' in sp_name:
                    sp_sku_code = convert_id2code('deli', sp_sku_id)
                item['supplierSkuCode'] = sp_sku_code

            item.pop('skuImg', '')
            item.pop('supplierName', '')
            bulk_list.append(UpdateOne({'_id': sku_id}, {'$set': item}, upsert=False))

    print(len(bulk_list))

    if bulk_list:
        mongo.bulk_write('item_data_pool', bulk_list)


if __name__ == '__main__':
    update_status(2019)